<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\util;

use think\facade\Cache;

/**
 * 缓存类
 * Class Caches
 * @package buwang\util
 */
class Caches
{
    /**
     * 标签名
     * @var string
     */
    protected static $globalCacheName = '_cached_1515146130';

    /**
     * 写入缓存
     */
    public static function set(string $name, $value, int $expire = null): bool
    {
        //这里不要去读取缓存配置，会导致死循环
        $expire = !is_null($expire) ? $expire : bw_config('cache_config') ?? 86400;
        if (!is_int($expire))
            $expire = (int)$expire;
        return self::handler()->set($name, $value, $expire);
    }

    /**
     * 如果不存在则写入缓存
     */
    public static function get(string $name, $default = false, int $expire = null)
    {
        //这里不要去读取缓存配置，会导致死循环
        $expire = !is_null($expire) ? $expire : bw_config('cache_config') ?? 86400;
        if (!is_int($expire))
            $expire = (int)$expire;
        return self::handler()->remember($name, $default, $expire);
    }

    /**
     * 删除缓存
     */
    public static function delete(string $name)
    {
        return Cache::delete($name);
    }

    /**
     * 缓存句柄
     */
    public static function handler()
    {
        return Cache::tag(self::$globalCacheName);
    }

    /**
     * 清空缓存池
     */
    public static function clear()
    {
        return self::handler()->clear();
    }
}